package com.imooc.girl.controller;

import com.imooc.girl.domain.Result;
import com.imooc.girl.respository.GirlRepostory;
import com.imooc.girl.service.GirlService;
import com.imooc.girl.domain.Girl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by 10077 on 2018/3/6.
 * desc:
 */
@RestController
public class GirlController {

    @Autowired
    private GirlRepostory girlRepostory;
    @Autowired
    private GirlService girlService;

//    表单验证
    @PostMapping("/girls")
    public Result<Girl> girlAdd(@Valid Girl girl , BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            Result result = new Result();
            result.setCode(1);
            result.setMsg(bindingResult.getFieldError().getDefaultMessage());
            return result;
        }
        girl.setCupSize(girl.getCupSize());
        girl.setAge(girl.getAge());

        Result result = new Result();
        result.setCode(0);
        result.setMsg("返回正确");
        result.setData(girlRepostory.save(girl));
        return result;
    }

    @GetMapping("/girls")
    public List<Girl> girlList(){
        return girlRepostory.findAll();
    }

    @PostMapping("girls")
    public Girl girlAdd(@RequestParam("cupSize")String cupSize,@RequestParam("age")Integer age){
        Girl girl = new Girl();
        girl.setAge(16);
        girl.setCupSize("d");
        return girlRepostory.save(girl);
    }

    @PostMapping(value = "/girls/{id}")
    public Girl getFindOne(@PathVariable("id")Integer id){
        return girlRepostory.getOne(id);
    }

    @PutMapping(value = "/girls/{id}")
    public Girl updateGirl(@PathVariable("id")Integer id,@RequestParam("cupSize")String cupSize,@RequestParam("age")Integer age){
        Girl girl = new Girl();
        girl.setId(id);
        girl.setCupSize(cupSize);
        girl.setAge(age);
        return girlRepostory.save(girl);
    }

    @DeleteMapping("/girls/{id}")
    public void deleteGirl(@PathVariable("id")Integer id) {
        girlRepostory.deleteById(id);
    }

    @GetMapping("/girls/age/{age}")
    public List<Girl> findByAge(@PathVariable("age") Integer age){
        return girlRepostory.findByAge(age);
    }

    @PostMapping(value = "/girls/two")
    public void insertTwo(){
        girlService.insertTwo();
    }

    @GetMapping(value = "girls/getAge/{id}")
    public void getAge(@PathVariable("id") Integer id) throws Exception{
        girlService.getAge(id);
    }
}
